package com.example.sharding.demo.service;

import com.example.sharding.demo.dao.UserMapper;
import com.example.sharding.demo.model.BaseEntity;
import com.example.sharding.demo.model.GlobalConstant;
import com.example.sharding.demo.model.table.User;
import com.example.sharding.demo.utils.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private GlobalService commonService;
    @Autowired
    private UserMapper userMapper;


    @Override
    public int insertUser(BaseEntity<User> record) {
        User user = this.findUser(new BaseEntity<User>(new User(record.getEntity().getId())));
        if (user != null) {
            return 1;
        }
        return userMapper.insertUser(record.getEntity());
    }

    @Override
    public User findUser(BaseEntity<User> record) {
        commonService.setQueryTimeRange(record);
        return userMapper.findUser(record);
    }

    @Override
    public int updateUser(BaseEntity<User> record) {
        User user = this.findUser(new BaseEntity<User>(new User(record.getEntity().getId())));
        if (user == null) {
            return 0;
        }
        User updateUser = record.getEntity();
        updateUser.setCreateTime(user.getCreateTime());
        //return userMapper.updateUser(updateUser);
        return 0;
    }

    @Override
    public int updateUserName(String name, Integer id) {
        User user = this.findUser(new BaseEntity<User>(new User(id)));
        if (user == null) {
            return 0;
        }
        String tableName = GlobalConstant.TABLE_NAME_USER_PRIFX + DateUtil.date2Str(user.getCreateTime(),DateUtil.YEAR_MONTH_NUMBER);
        return userMapper.updateUserName(tableName, name, id);
    }

    @Override
    public int countUserByName(String name) {
        return userMapper.countUserByName(name);
    }

    @Override
    public List<User> findUserList(BaseEntity<User> record) {
        commonService.setQueryTimeRange(record);
        return userMapper.findUserList(record);
    }

    @Override
    public PageInfo<User> findUserPage(BaseEntity<User> record, Page<User> page) {
        commonService.setQueryTimeRange(record);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<User> list = userMapper.findUserList(record);
        return new PageInfo<>(list);
    }


}
